// pages/profile/profile.js
Page({
  data: {
    openid: '',
    stats: {
      totalPhotos: 0,
      thisMonth: 0
    },
    storageStats: {
      totalFiles: 0,
      totalSize: '0 KB',
      standardCount: 0,
      hdCount: 0
    },
    showStatsDialog: false
  },

  onLoad() {
    this.checkLogin()
    this.loadUserStats()
  },

  onShow() {
    this.checkLogin()
    this.loadUserStats()
  },

  checkLogin() {
    const openid = wx.getStorageSync('openid')
    this.setData({ openid })
  },

  async loadUserStats() {
    const openid = wx.getStorageSync('openid')
    if (!openid) return

    try {
      const app = getApp();
      const apiUrl = app.globalData.api_url;
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: apiUrl + 'api/user/stats',
          method: 'GET',
          header: {
            'openid': openid
          },
          success: resolve,
          fail: reject
        })
      })

      if (response.data && response.data.success) {
        this.setData({
          stats: response.data.data.stats,
          storageStats: response.data.data.storage
        })
      }
    } catch (error) {
      console.error('加载用户统计失败:', error)
    }
  },

  goToGallery() {
    wx.navigateTo({
      url: '/pages/gallery/gallery'
    })
  },

  async showStorageStats() {
    const openid = wx.getStorageSync('openid')
    if (!openid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    try {
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: apiUrl + 'api/user/storage',
          method: 'GET',
          header: {
            'openid': openid
          },
          success: resolve,
          fail: reject
        })
      })

      if (response.data && response.data.success) {
        this.setData({
          storageStats: response.data.data,
          showStatsDialog: true
        })
      }
    } catch (error) {
      console.error('获取存储统计失败:', error)
      wx.showToast({
        title: '获取失败，请重试',
        icon: 'none'
      })
    }
  },

  clearCache() {
    wx.showModal({
      title: '清理缓存',
      content: '确定要清理本地缓存吗？此操作不会影响已保存的照片。',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorageSync()
          wx.showToast({
            title: '清理成功',
            icon: 'success'
          })
          this.setData({
            stats: { totalPhotos: 0, thisMonth: 0 }
          })
        }
      }
    })
  },

  showAbout() {
    wx.showModal({
      title: '关于我们',
      content: '证件照大师 v1.0.0\n\n专业的证件照制作工具，支持多种尺寸和背景颜色，让您的证件照更专业！\n\n开源项目地址：\nhttps://gitee.com/ezemeti/PhotoAI\n\n开源协议：MIT License\n- 允许自由使用、修改和分发\n- 禁止商业用途\n- 保留原作者版权声明',
      showCancel: false
    })
  },

  logout() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('openid')
          wx.removeStorageSync('token')
          wx.showToast({
            title: '已退出',
            icon: 'success'
          })
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/login/login'
            })
          }, 1500)
        }
      }
    })
  },

  onStatsClose() {
    this.setData({ showStatsDialog: false })
  }
})